package fr.ece.ing4.si.singlethread;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

import fr.ece.ing4.si.gui.FirstWindow;

public class McSimulation {

		
		public double MonteCarloStandardOption (String CallPutFlag, double S, double X, double T, double r, double b, double v, int nSteps, int nSimulations) {
			
			//declarations
			double dt, St;
			double Sum=0, Drift, vSqrdt;
			int i, j, z=0;
			Random random;
			
			//variables keeping track of execution time
			long start;
			long end;
			
			random = new Random ();
			
			//get the starting time
			start = System.currentTimeMillis();
			
			dt = T/nSteps;
			Drift = (b-(v*v)/2) * dt;
			vSqrdt = v*Math.sqrt(dt);
			
			if(CallPutFlag.equals("c"))
			{
				z = 1;
			}
			else if(CallPutFlag.equals("p"))
			{
				z = -1;
			}
			
			for(i = 0; i < nSimulations; i++)
			{
				St = S;
				for(j = 0; j < nSteps; j++)
				{
					St = St*Math.exp(Drift + vSqrdt * random.nextGaussian());
				}
				
				Sum = Sum + Math.max(z*(St-X), 0);
			}
			
			//get the ending execution time
			end = System.currentTimeMillis();
			
			//calculate and print the execution time
			System.out.println("execution time for the simulation: " + (end-start) + " ms");
			
			return (Math.exp(-r*T) * (Sum/nSimulations));
			
		}
	
			
		public void McSimSingle () throws IOException
		{
			
			//File (sim.txt) reading
			final BufferedReader reader = new BufferedReader( new FileReader("sim.txt"));
				       
			final String data = reader.readLine(); //read one line
			
			final String[] dataItems = data.split(",");//put each data from the line in an array
			
			//do a simulation
			final double result = MonteCarloStandardOption(dataItems[0], Double.valueOf(dataItems[1]), Double.valueOf(dataItems[2]), Double.valueOf(dataItems[3]), Double.valueOf(dataItems[4]), Double.valueOf(dataItems[5]), Double.valueOf(dataItems[6]), Integer.valueOf(dataItems[7]), Integer.valueOf(dataItems[8]));
				    
			//print the simulation result
			System.out.println("result of MC simulation: " + result );
			
			
		}
		
		public static void main(final String [] args) {
			

			javax.swing.SwingUtilities.invokeLater(new Runnable()
			{
				public void run()
				{
					//declarations
					FirstWindow win = new FirstWindow();
					McSimulation mcsim = new McSimulation();
					
					try {
						mcsim.McSimSingle(); //do a MC simulation
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} //do a simulation
					
				}
				
			});
			
			
		}

}
